package cn.ug.activity.web.job;

import cn.ug.activity.bean.CouponNoticeBean;
import cn.ug.activity.mapper.CouponMemberMapper;
import cn.ug.activity.mapper.entity.CouponDonation;
import cn.ug.activity.mapper.entity.CouponMember;
import cn.ug.activity.mapper.entity.CouponRepertory;
import cn.ug.activity.service.CouponDonationService;
import cn.ug.activity.service.CouponMemberService;
import cn.ug.activity.service.CouponRepertoryService;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.RedisGlobalLock;
import cn.ug.feign.MemberUserService;
import cn.ug.member.bean.MemberInfoBean;
import cn.ug.msg.mq.Msg;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static cn.ug.config.QueueName.QUEUE_MSG_SEND;
import static cn.ug.util.ConstantUtil.COMMA;

@Component
public class CouponDonationTask {
    @Resource
    private RedisGlobalLock redisGlobalLock;
    @Autowired
    private CouponDonationService couponDonationService;
    @Autowired
    private CouponRepertoryService couponRepertoryService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private CouponMemberService couponMemberService;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private CouponMemberMapper couponMemberMapper;

    @Scheduled(cron = "0 0 1 * * ?")
    public void donateCoupon() {
        List<CouponDonation> data = couponDonationService.listRecords(UF.getFormatDateTime("yyyy-MM-dd", UF.getDateTime()));
        if (data == null || data.size() == 0) {
            return;
        }
        String key = "CouponDonationTask:donateCoupon:" + UF.getFormatDateTime("yyyy-MM-dd", UF.getDateTime());
        if(!redisGlobalLock.lock(key, 1, TimeUnit.DAYS)) {
            return;
        }
        try {
            for (CouponDonation entity : data) {
                if (StringUtils.isBlank(entity.getCouponIds())) {
                    return;
                }
                List<Integer> ids = new ArrayList<Integer>();
                String[] idsInfo = StringUtils.split(entity.getCouponIds(), COMMA);
                if (idsInfo != null && idsInfo.length > 0) {
                    for (int i = 0; i < idsInfo.length; i++) {
                        ids.add(Integer.parseInt(idsInfo[i]));
                    }
                }
                String mark = "";
                if (entity.getType() == 0) {
                    mark = "mg黄金红包";
                } else if (entity.getType() == 2) {
                    mark = "元商城满减券";
                }
                final String desc = mark;
                final String noticeType = entity.getNoticeType();
                List<CouponRepertory> couponRepertories = couponRepertoryService.findByIds(ids);
                if (couponRepertories != null && couponRepertories.size() > 0) {
                    SerializeObject<Integer> bean = memberUserService.countTotalUsers();
                    if (null != bean && bean.getCode() == ResultType.NORMAL) {
                        int num = bean.getData();
                        entity.setTotalQuantity(num);
                        int pages = PaginationUtil.getTotalPage(num, 1000);
                        for (int i = 0; i < entity.getQuantity(); i++) {
                            if (entity.getTargetType() == 1) {
                                int page = 0;
                                if (couponDonationService.modifyStatus(entity.getId(), 4)) {
                                    couponDonationService.save(entity);
                                    for (int j = 0; j < pages; j++) {
                                        page = j + 1;
                                        SerializeObject<DataTable<MemberInfoBean>> usersBean = memberUserService.listUserId(page, 1000);
                                        if (null != usersBean && usersBean.getCode() == ResultType.NORMAL && usersBean.getData() != null) {
                                            List<MemberInfoBean> users = usersBean.getData().getDataList();
                                            List<CouponMember> coupons = new ArrayList<CouponMember>();
                                            int discountAmount = 0;
                                            for (CouponRepertory couponRepertory : couponRepertories) {
                                                discountAmount += couponRepertory.getDiscountAmount();
                                            }
                                            for (MemberInfoBean user : users) {
                                                for (CouponRepertory couponRepertory : couponRepertories) {
                                                    CouponMember couponMember = new CouponMember();
                                                    couponMember.setAddTime(UF.getFormatDateTime(LocalDateTime.now()));
                                                    couponMember.setMemberId(user.getId());
                                                    couponMember.setCouponId(couponRepertory.getId());
                                                    coupons.add(couponMember);
                                                }
                                            }
                                            couponMemberService.save(coupons);
                                            if (entity.getIsNotice() == 2 && discountAmount > 0) {
                                                for (MemberInfoBean user : users) {
                                                    Msg msg = new Msg();
                                                    msg.setMemberId(user.getId());
                                                    msg.setMobile(user.getMobile());
                                                    msg.setNoticeType(noticeType);
                                                    msg.setType(cn.ug.msg.bean.status.CommonConstants.MsgType.GIVE_COUPON.getIndex());
                                                    Map<String, String> paramMap = new HashMap<>();
                                                    paramMap.put("couponInfo", discountAmount+desc);
                                                    msg.setParamMap(paramMap);
                                                    amqpTemplate.convertAndSend(QUEUE_MSG_SEND, msg);
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                if (StringUtils.isNotBlank(entity.getMobiles())) {
                                    SerializeObject<List<MemberInfoBean>> resultBean = memberUserService.listUserId(String.valueOf(entity.getId()));
                                    if (null != resultBean && resultBean.getCode() == ResultType.NORMAL && resultBean.getData() != null) {
                                        List<MemberInfoBean> users = resultBean.getData();
                                        if (couponDonationService.modifyStatus(entity.getId(), 4)) {
                                            List<CouponMember> coupons = new ArrayList<CouponMember>();
                                            entity.setTotalQuantity(users.size());
                                            couponDonationService.save(entity);
                                            int discountAmount = 0;
                                            for (CouponRepertory couponRepertory : couponRepertories) {
                                                discountAmount += couponRepertory.getDiscountAmount();
                                            }
                                            for (MemberInfoBean user : users) {
                                                for (CouponRepertory couponRepertory : couponRepertories) {
                                                    CouponMember couponMember = new CouponMember();
                                                    couponMember.setAddTime(UF.getFormatDateTime(LocalDateTime.now()));
                                                    couponMember.setMemberId(user.getId());
                                                    couponMember.setCouponId(couponRepertory.getId());
                                                    coupons.add(couponMember);
                                                }
                                            }
                                            couponMemberService.save(coupons);
                                            if (entity.getIsNotice() == 2 && discountAmount > 0) {
                                                for (MemberInfoBean user : users) {
                                                    Msg msg = new Msg();
                                                    msg.setMemberId(user.getId());
                                                    msg.setMobile(user.getMobile());
                                                    msg.setNoticeType(noticeType);
                                                    msg.setType(cn.ug.msg.bean.status.CommonConstants.MsgType.GIVE_COUPON.getIndex());
                                                    Map<String, String> paramMap = new HashMap<>();
                                                    paramMap.put("couponInfo", discountAmount+desc);
                                                    msg.setParamMap(paramMap);
                                                    amqpTemplate.convertAndSend(QUEUE_MSG_SEND, msg);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } finally {
            //redisGlobalLock.unlock(key);
        }
    }


    @Scheduled(cron = "0 0 9 * * ?")
    //@Scheduled(cron = "0 26 17 * * ?")
    public void couponBecomeDueForNotice() {
        String key = "CouponDonationTask:couponBecomeDueForNotice:" + UF.getFormatDateTime("yyyy-MM-dd", UF.getDateTime());
        if(!redisGlobalLock.lock(key, 1, TimeUnit.DAYS)) {
            return;
        }
        List<CouponNoticeBean> beans = couponMemberMapper.queryForNoticeList();
        if (beans != null && beans.size() > 0) {
            for (CouponNoticeBean bean : beans) {
                Msg msg = new Msg();
                msg.setMemberId(bean.getMemberId());
                msg.setMobile(bean.getMobile());
                msg.setType(cn.ug.msg.bean.status.CommonConstants.MsgType.COUPON_BECOME_DUE.getIndex());
                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("days", String.valueOf(bean.getPrecedeDays()));
                msg.setParamMap(paramMap);
                amqpTemplate.convertAndSend(QUEUE_MSG_SEND, msg);
            }
        }
    }
}
